package com.winit.openapi.sms;

import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.winit.common.query.Page;
import com.winit.common.spi.SPIException;
import com.winit.common.spi.context.CommandContext;
import com.winit.erp.spi.bpartner.vo.Bpartner;
import com.winit.openapi.constants.ApiConstant;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.sms.common.SmsUtils;
import com.winit.openapi.util.DateUtil;
import com.winit.sms.spi.base.bankcollection.BankCollectionService;
import com.winit.sms.spi.base.bankcollection.command.QueryBankCollectionByBankIdCommand;
import com.winit.sms.spi.base.bankcollection.vo.BankCollectionVo;
import com.winit.sms.spi.common.vo.PageVo;
import com.winit.sms.spi.wallet.offlinerecharge.OffLineRechargeService;
import com.winit.sms.spi.wallet.offlinerecharge.command.CreateOffLineRechargeCommand;
import com.winit.sms.spi.wallet.offlinerecharge.command.ModifyOffLineRechargeByIdCommand;
import com.winit.sms.spi.wallet.offlinerecharge.command.ModifyOffLineRechargeByIdOpenAPICommand;
import com.winit.sms.spi.wallet.offlinerecharge.command.QueryOffLineRechargeByNoCommand;
import com.winit.sms.spi.wallet.offlinerecharge.command.QueryOffLineRechargeCommand;
import com.winit.sms.spi.wallet.offlinerecharge.command.QueryOffLineRecordCommand;
import com.winit.sms.spi.wallet.offlinerecharge.vo.OffLineRechargeVo;

/**
 * 线下充值单
 * 
 * @version <pre>
 * Author	Version		Date		Changes
 * jun.lu 	1.0  		2016年1月11日 	Created
 * 
 * </pre>
 * @since 1.
 */
@Controller
@RequestMapping("/sms/offLineRecharge")
public class OffLineRechargeController extends BaseController {

    private static Logger          logger = LoggerFactory.getLogger(OffLineRechargeController.class);
    @Autowired
    private OffLineRechargeService offLineRechargeService;

    @Resource
    private BankCollectionService  bankCollectionService;

    /**
     * 创建线下充值单
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/createOffLineRecharge")
    public String createOffLineRecharge(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
    	try {
    		CreateOffLineRechargeCommand command = SmsUtils.toJavaObject(requestMsg.getData(),
    	            CreateOffLineRechargeCommand.class);
	        logger.info(">>>>>>>>>>>>>>>>>>>>>>>>createOffLineRecharge:" + command.toString());
	        Bpartner bpartner = CommandContext.getContext().get(ApiConstant.API_BPARTNER);
	        if (bpartner == null) {
	            logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>bpartner对象为空");
	            return ERROR;
	        }
	        QueryBankCollectionByBankIdCommand queryBankCollectionByBankIdCommand = new QueryBankCollectionByBankIdCommand();
	        queryBankCollectionByBankIdCommand.setBankaccountId(command.getBankAccountNo());
	        queryBankCollectionByBankIdCommand.setCollectionOrgId(CommandContext.getContext().getOrgId());
	        BankCollectionVo bankCollectionVo = bankCollectionService.queryBankCollectionByBankId(queryBankCollectionByBankIdCommand);
	        if (null != bankCollectionVo) {
	            command.setBillBpartnerCode(bankCollectionVo.getCustomerCode());
	            command.setSupplierCode(bankCollectionVo.getSupplierCode());
	            command.setCollectionOrgId(bankCollectionVo.getCollectionOrgId());
	        }
	        command.setCustomerCode(bpartner.getValue());
	        command.setDocumentSource("SO");
	        command.setCtx(CommandContext.getContext());
	        command.setOrgId(CommandContext.getContext().getOrgId());
	        String rechargeNo = offLineRechargeService.createOffLineRecharge(command);

	        QueryOffLineRechargeByNoCommand queryOffLineRechargeByNoCommand = new QueryOffLineRechargeByNoCommand();
	        queryOffLineRechargeByNoCommand.setRechargeNo(rechargeNo);
	        OffLineRechargeVo offLineRechargeVo = offLineRechargeService.queryOffLineRechargeByNo(queryOffLineRechargeByNoCommand);
	        if (offLineRechargeVo != null) {
	            responseMsg.setData(offLineRechargeVo.getId());
	        }
		} catch (SPIException e) {
			logger.error("createOffLineRecharge-----》创建线下充值单异常",e);
            responseMsg.setCode(e.getErrorCode());
            responseMsg.setMsg(e.getErrorMsg());
            return ERROR;
		}
        return SUCCESS;
    }

    /**
     * 分页查询线下充值单
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping("/pageOffLineRecharge")
    public String pageOffLineRecharge(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {

        QueryOffLineRechargeCommand command = SmsUtils.toJavaObject(requestMsg.getData(),
            QueryOffLineRechargeCommand.class);

        PageVo pageVo = SmsUtils.SetPageParams(requestMsg.getData());
        command.setPageVo(pageVo);
        Bpartner bpartner = CommandContext.getContext().get(ApiConstant.API_BPARTNER);
        if (bpartner == null) {
            logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>bpartner对象为空");
            return ERROR;
        }
        command.setCustomerCode(bpartner.getValue());
        if (null != command.getPayEndDate()) {
            command.setPayEndDate(DateUtil.spliceDate(command.getPayEndDate()));
        }
        Page<OffLineRechargeVo> pagelist = offLineRechargeService.pageOffLineRecharge(command);
        Map<String, Object> data = SmsUtils.setPageData(pagelist);
        responseMsg.setData(data);
        return SUCCESS;
    }

    /**
     * 查看线下充值单详情
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping("/queryOffLineRecord")
    public String queryOffLineRecord(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {

        //        QueryOffLineRechargeByNoCommand command = SmsUtils.toJavaObject(requestMsg.getData(),
        //            QueryOffLineRechargeByNoCommand.class);
        //        OffLineRechargeVo offLineRecharge = offLineRechargeService.queryOffLineRechargeByNo(command);

        QueryOffLineRecordCommand command = SmsUtils.toJavaObject(requestMsg.getData(), QueryOffLineRecordCommand.class);
        OffLineRechargeVo offLineRecharge = offLineRechargeService.queryOffLineRecord(command);
        responseMsg.setData(offLineRecharge);
        return SUCCESS;

    }

    /**
     * 根据ID编辑线下充值单
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping("/modifyOffLineRechargeById")
    public String modifyOffLineRechargeById(@ModelAttribute RequestMsg requestMsg,
                                            @ModelAttribute ResponseMsg responseMsg) {
        ModifyOffLineRechargeByIdOpenAPICommand command = SmsUtils.toJavaObject(requestMsg.getData(),
            ModifyOffLineRechargeByIdOpenAPICommand.class);
        ModifyOffLineRechargeByIdCommand newCommand = new ModifyOffLineRechargeByIdCommand();
        org.springframework.beans.BeanUtils.copyProperties(command, newCommand);
        newCommand.setCtx(CommandContext.getContext());
        Integer retValue = offLineRechargeService.modifyOffLineRechargeById(newCommand);
        responseMsg.setData(retValue);
        return SUCCESS;
    }

    /**
     * 线下充值单作废
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping("/modifyCancelOffLineRecharge")
    public String modifyCancelOffLineRecharge(@ModelAttribute RequestMsg requestMsg,
                                              @ModelAttribute ResponseMsg responseMsg) {

        Object params = requestMsg.getData();
        JSONObject json = null;
        if (params instanceof JSONObject) {
            json = (JSONObject) params;
            Object obj = json.get("id");
            if (obj != null && StringUtils.isNotBlank(obj.toString())) {
                Long id = Long.valueOf(obj.toString());
                QueryOffLineRecordCommand queryOffLineRecordCommand = new QueryOffLineRecordCommand();
                queryOffLineRecordCommand.setId(id);
                OffLineRechargeVo offLineRecharge = offLineRechargeService.queryOffLineRecord(queryOffLineRecordCommand);
                if (offLineRecharge == null) {
                    logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>id：{} 不存在此充值单", id);
                } else {
                    //草稿状态下作废
                    if ("DR".equals(offLineRecharge.getStatus())) {
                        ModifyOffLineRechargeByIdCommand command = new ModifyOffLineRechargeByIdCommand();
                        command.setId(id);
                        command.setStatus("VO");
                        offLineRechargeService.modifyOffLineRechargeById(command);
                    } else {
                        logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>id：{} 此充值单不是草稿状态，不能作废", id);
                    }
                }
            }
        } else {
            logger.info("JSON格式错误: {}", json);
            throw new ApiException(ErrorCode.ILLEGAL_JSON_STRING);
        }

        return SUCCESS;
    }
    
    /**
     * 卖家网站-线下充值单导出 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping("/exportOfflineRecharge")
    public String exportOfflineRecharge(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
    	QueryOffLineRechargeCommand command = SmsUtils.toJavaObject(requestMsg.getData(), QueryOffLineRechargeCommand.class);
		Bpartner bpartner = CommandContext.getContext().get(ApiConstant.API_BPARTNER);
		if (bpartner == null) {
			logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>bpartner对象为空");
			return ERROR;
		}
		command.setCustomerCode(bpartner.getValue());
		if (null != command.getPayEndDate()) {
			command.setPayEndDate(DateUtil.spliceDate(command.getPayEndDate()));
		}
		
		String path = "";
		try {
			path = offLineRechargeService.exportOffLineRecharge(command);
		} catch (SPIException e) {
			logger.error(e.getMessage());
            responseMsg.setCode(e.getErrorCode());
            responseMsg.setMsg(e.getErrorMsg());
            responseMsg.setData(com.winit.sms.spi.common.constant.Constants.UPLOAD_FA);
            return ERROR;
		}
		responseMsg.setData(path);
    	return SUCCESS;
    }
    
    /**
     * 生成线下充值电子收据 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping("/generateOffLineReceipt")
    public String generateOffLineReceipt(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
    	ModifyOffLineRechargeByIdCommand command = new ModifyOffLineRechargeByIdCommand();
    	try {
    		command = SmsUtils.toJavaObject(requestMsg.getData(), ModifyOffLineRechargeByIdCommand.class);
			CommandContext ctx = CommandContext.getContext();
			command.setCtx(ctx);
			String url = offLineRechargeService.generateOffLineReceipt(command);
			responseMsg.setData(url);
		} catch (SPIException e) {
			logger.error("线下充值单生成电子收据异常，ID:{},{}", command.getId() + "", e.getMessage());
            responseMsg.setCode(e.getErrorCode());
            responseMsg.setMsg(e.getErrorMsg());
            return ERROR;
		}
    	return SUCCESS;
    }
    
}
